package com.vm.fragment;

import java.io.File;
import java.util.List;

import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.activity.DetailActivity;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.model.ActiveSoft;
import com.vm.model.DownInfo;
import com.vm.model.Soft;
import com.vm.myview.ViewDownUtils;
import com.vm.utils.ApkUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyVolley;
import com.vm.utils.SoftDataUtil;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "InflateParams", "ShowToast" })
public class DownloadedFragment extends BaseFragment {
	ListView lv_downloading;
	DownInfoDao infoDao;
	ViewDownUtils viewDownUtils;
	ActiveSoft activeSoft;
	LinearLayout found_ll_1;
	Button btn_download;
	private View view;
	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;
	RequestQueue mQueue;

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				mainhandler.sendMessage(new Message());
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(300);
					// 在这里添加调用接口获取数据的代码

					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功

					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				// UIHelper.hideDialogForLoading();
			}
		}.execute();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("DownloadingFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.download_complete, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Log.i("DownloadingFragment", "onActivityCreated");

		isPrepared = true;
		lazyLoad();

	}

	public void init() {
		found_ll_1 = (LinearLayout) view.findViewById(R.id.found_ll_1);
		infoDao = new DownInfoDao(getActivity());
		List<DownInfo> list = infoDao.getDownloaded();
		if (list != null) {
			int i = 0;
			for (DownInfo downInfo : list) {
				activeSoft = new ActiveSoft();
				activeSoft.setSoftId(downInfo.getSoftId());
				activeSoft.setName(downInfo.getName());
				activeSoft.setImageUrl(downInfo.getImageUrl());
				found_ll_1.addView(dyAddView(i, activeSoft, 1));
				i++;
			}
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mainhandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			init();
		};
	};

	public LinearLayout dyAddView(int i, final ActiveSoft activeSoft,
			int progress) {
		mQueue = MyVolley.getRequestQueue();
		LinearLayout linearLayout = (LinearLayout) getActivity()
				.getLayoutInflater().inflate(R.layout.found_item, null);
		// RelativeLayout rlayout_info = (RelativeLayout) linearLayout
		// .findViewById(R.id.rlayout_info);

		TextView tv_softName = (TextView) linearLayout
				.findViewById(R.id.tv_softName);
		ImageView iv_softImage = (ImageView) linearLayout
				.findViewById(R.id.iv_softImage);
		final TextView tv_softSize = (TextView) linearLayout
				.findViewById(R.id.tv_softSize);
		final TextView tv_software_introduction = (TextView) linearLayout
				.findViewById(R.id.tv_software_introduction);
		final TextView tv_download_number = (TextView) linearLayout
				.findViewById(R.id.tv_download_number);
		final RatingBar rb_star = (RatingBar) linearLayout
				.findViewById(R.id.rb_star);

		btn_download = (Button) linearLayout.findViewById(R.id.btn_download);
		String url = VMConst.DETAIL_URL + activeSoft.getSoftId();
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						// TODO Auto-generated method stub
						Soft soft = new Soft();
						soft = JsonUtils.jsonToBean(arg0, Soft.class);
						if (soft.getDownload() != null) {
							String download = SoftDataUtil.getSoftDownload(soft.getDownload());
							tv_download_number.setText(download);
						}
						if (soft.getInAWord() != null) {
							tv_software_introduction.setText(soft.getInAWord());
						} else {
							tv_software_introduction.setText("");
						}
						// 大小
						if (soft.getSize() != null) {
							float size = soft.getSize();
							tv_softSize.setText(Float.toString(size) + "M");
						}
						// 星级
						if (soft.getStar() != null) {
							float fstar = soft.getStar();
							rb_star.setRating(fstar / 2);
						}
					}

				}, null);
		mQueue.add(jsonObjectRequest);
		btn_download.setTag(activeSoft.getName());
		boolean isInstalled = ApkUtils.isAppInstalled(
				activeSoft.getPackageName(), getActivity());
		if (isInstalled) {
			btn_download.setText("已安装");
			btn_download.setBackgroundResource(R.drawable.installed_border);
			btn_download.setTextColor(getActivity().getResources().getColor(
					R.color.installed_color));
		} else {
			File apkfile = new File(
					StringUtil.getSdApkUrl(activeSoft.getName()));
			if (apkfile.exists()) {
				btn_download.setText("安装");
				btn_download
						.setBackgroundResource(R.drawable.installation_border);
				btn_download.setTextColor(getActivity().getResources()
						.getColor(R.color.installation_color));
				btn_download.setOnClickListener(downClickListener);
			} else {
				btn_download.setVisibility(View.GONE);
			}
		}

		if (activeSoft.getName() != null) {
			// String softName =
			// StringUtil.getShotName(soft.getName());
			tv_softName.setText(activeSoft.getName());
		}

		ImageLoader.getInstance().displayImage(
				VMConst.URL + activeSoft.getImageUrl(), iv_softImage,
				MyDisplayImageOptions.getInstance());

		OnClickListener ll_listener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), DetailActivity.class);

				intent.putExtra("softId", activeSoft.getSoftId());
				getActivity().startActivityForResult(intent, 10);
			}
		};
		linearLayout.setOnClickListener(ll_listener);
		/**
		 * 加载一些列下载有关的东西
		 */

		// downloadService.initProgressBar(soft);
		return linearLayout;
	}

	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			// 执行安装
			Toast toast3 = Toast.makeText(getActivity(), "正在安装", 500);
			toast3.setGravity(Gravity.CENTER, 0, 0);
			toast3.show();

			String tag = v.getTag().toString();
			File apkfile = new File(StringUtil.getSdApkUrl(tag));
			if (!apkfile.exists()) {
				return;
			}
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
					"application/vnd.android.package-archive");
			v.getContext().startActivity(i);

		}
	};
}